import  {useEffect, useState} from 'react';
import {Select} from 'antd';
import {useRequest} from 'ahooks';
import {getRegionInfoTree} from '@/services/db/public';

const AreaSelect = (props: any) => {
    const [options, setOptions] = useState([]);
    const regionInfoTree = useRequest(
        () =>
            getRegionInfoTree({
                zoneCode: props.zoneCode,
                depth: 1,
            }),
        {
            manual: true,
            onSuccess(data: any) {
                if (!(data && data.length)) {
                    return false;
                }
                let areaOptions: any = [];
                data.forEach((item: any) => {
                    areaOptions.push({
                        label: item.name,
                        value: item.id,
                    });
                    if (item.children) {
                        item.children.forEach((childItem: any) => {
                            areaOptions.push({
                                label: childItem.name,
                                value: childItem.id,
                            });
                        });
                    }
                });
                setOptions(areaOptions);
                props.onChange && props.onChange(areaOptions[0].value);
            },
        },
    );
    useEffect(() => {
        regionInfoTree.run();
    }, [props.zoneCode]);
    return (
        <Select
            placeholder="请选择区域"
            options={options}
            value={props.value}
            onChange={props.onChange}
        ></Select>
    );
}

export default AreaSelect;
